﻿using System;
using System.Windows.Forms;
using System.Data.SQLite;
using Dapper;

namespace SoftLab.Formularios
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void btnIngresar_Click(object sender, EventArgs e)
        {
            using (var conexion = new SQLiteConnection(Properties.Settings.Default.ConnectionString))
            {
                conexion.Open();
                const string comando = "SELECT username,password,permisos FROM usuario WHERE username=@username LIMIT 1";
                var login = conexion.Query(comando, new {username = txtUsuario.Text});
                foreach (var l in login)
                {
                    var user = l.username;
                    var pass = l.password;
                    if (Clases.Codificador.EncodeMd5(txtPassword.Text) == pass)
                    {
                        // ReSharper disable once ObjectCreationAsStatement
                        new SaveUser
                        {
                            User = user,
                            Password = pass
                        };
                        var p = new Principal();
                        p.Show();
                        Close();
                    }
                    else
                        MessageBox.Show("Error en el usuario o contraseña", "Error");
                }
            }
        }

        private void txtUsuario_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                SendKeys.Send("{TAB}");
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                SendKeys.Send("{TAB}");
        }

        private void btnSalir_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }

    internal class SaveUser
    {
        public string User { get; set; }
        public string Password { get; set; }
    }
}
